package com.ruiboyun.liveapp.ui;


import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ruiboyun.liveapp.R;
import com.ruiboyun.liveapp.adapter.ChannelAdapter;
import com.ruiboyun.liveapp.base.BaseActivity;
import com.ruiboyun.liveapp.bean.Channel;
import com.ruiboyun.liveapp.bean.ChannelEntity;
import com.ruiboyun.liveapp.bean.Share;
import com.ruiboyun.liveapp.bean.UpdatePortEvent;
import com.ruiboyun.liveapp.dialog.BaseDialog;
import com.ruiboyun.liveapp.dialog.SharePopupWindow;
import com.ruiboyun.liveapp.listener.OnItemClickListener;
import com.ruiboyun.liveapp.presenter.ChannelPresenter;
import com.ruiboyun.liveapp.presenter.impl.ChannelPresenterImpl;
import com.ruiboyun.liveapp.util.tool.ToasUtil;
import com.ruiboyun.liveapp.view.ChannelView;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainActivity extends BaseActivity implements ChannelView, OnItemClickListener, ChannelAdapter.OnLiveListener {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private ChannelPresenter channelPresenter;

    private List<Channel> channelList = new ArrayList<>();


    SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            stopRefresh(refreshLayout);
            channelPresenter.getChannel();
        }
    };
    private ChannelAdapter channelAdapter;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UpdatePortEvent event) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_channel;
    }

    @Override
    protected void afterCreate(@Nullable Bundle savedInstanceState) {
        channelPresenter = new ChannelPresenterImpl(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        channelAdapter = new ChannelAdapter(this,channelList);
        channelAdapter.setOnLiveListener(this);
        channelAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(channelAdapter);
        EventBus.getDefault().register(this);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(this, R.color.blue_login));
        refreshLayout.setOnRefreshListener(listener);
        refreshLayout.setRefreshing(true);
        listener.onRefresh();
        MPermissions.requestPermissions(this, 103, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO);


    }
    @OnClick({R.id.setting})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.setting:
                launcher(SettingActivity.class);
                break;
        }
    }
    @PermissionDenied(102)
    public void cameraError(){

    }
    @PermissionGrant(102)
    public void cameraSuccess(){
        LiveActivity.go(this, JSON.toJSONString(channel));
    }
    @PermissionDenied(103)
    public void fileError(){
        Toast.makeText(this,"直播请开启相机和录音权限",Toast.LENGTH_SHORT).show();
    }
    @PermissionGrant(103)
    public void fileSuccess(){

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this,requestCode,permissions,grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void getChannelSucces(ChannelEntity channelEntity) {
        channelList.clear();
        if (channelEntity.getChannels()!=null){
            channelList.addAll(channelEntity.getChannels());

        }
        channelAdapter.notifyDataSetChanged();
    }

    @Override
    public void showTips(String msg) {
        ToasUtil.showCenterToast(msg);
    }

    @Override
    public void onItemClick(int position) {

    }
    private Channel channel;
    @Override
    public void onLive(Channel channel) {
        this.channel=channel;
        long time = System.currentTimeMillis();
        if (time<channel.getStart_time()){
            showTipsDialog("当前时间早于开始直播时间，请耐心等待!");
        }else if (time>channel.getEnd_time()&&channel.getEnd_time()!=0){
            showTipsDialog("已错过直播时间，请下次再直播吧!");
        }else {
            MPermissions.requestPermissions(this, 102, Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO);


        }

    }

    @Override
    public void onShare(View view, Channel channel) {
        Share share=new Share();
        share.setTitle(channel.getTitle());
        share.setContent(channel.getDesc());
        share.setUrl(channel.getPlay_addr());
        share.setLogo(channel.getCover_addr());
        SharePopupWindow sharePopupWindow=new SharePopupWindow(this,share);
        sharePopupWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
    }

    private void showTipsDialog(String s) {
        BaseDialog baseDialog=new BaseDialog(this);
        baseDialog.setContent(s);
        baseDialog.setOnConfirmListener(new BaseDialog.OnConfirmListener() {
            @Override
            public void onConfirm() {

            }

            @Override
            public void onCancle() {

            }
        });
        baseDialog.show();
    }
    private long lastTime;

    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - lastTime > 1000) {
            lastTime = System.currentTimeMillis();
            ToasUtil.showCenterToast("再按一次退出");
        } else {

            super.onBackPressed();
        }

    }

    @Override
    public void onReview(Channel channel) {
        ReviewActivity.go(this,channel.getId());
    }
}
